<template>
  <div class="login">
    <div class="login-main">
      <!--<div class="main-left">-->
      <!--  <img src="../../assets/images/loginleftbg.png" alt="" />-->
      <!--</div>-->
      <div class="" style="width: 100%;position: relative">
        <!--<div class="logo">-->
        <!--  <img @click="openDialog" src="../../assets/images/logo.png" alt="" />-->
        <!--</div>-->

        <div class="loginTab">
          <div class="password" :class="current == 0 ? 'active' : ''" @click="tabClick(0)">
            <div>密码登录</div>
            <div v-if="current == 0" class="bottomLine"></div>
          </div>
          <div class="loginCode" :class="current == 1 ? 'active' : ''" @click="tabClick(1)">
            <div>验证码登录</div>
            <div v-if="current == 1" class="bottomLine"></div>
          </div>
        </div>
        <div v-if="current == 1" class="login-form" style="margin-top: 0px">
          <el-form
            autoComplete="on"
            :model="loginForm"
            :rules="loginRules"
            ref="loginForm"
            label-position="left"
          >
            <!--<h2 class="login-title">欢迎登录</h2>-->

            <!-- 手机号 -->
            <el-form-item prop="phoneNumber">
              <el-input
                name="phoneNumber"
                v-model="loginForm.phoneNumber"
                placeholder="请输入手机号"
                maxlength="11"
                @input="phoneInputFun"
              >
                <template slot="prefix">
                  <img src="../../assets/icon/phoneIcon.png" style="width: 16px;height: 25.16px;margin-top: 12px;margin-left: 13px" alt="">
                </template>
              </el-input>
            </el-form-item>
            <!-- 验证码 -->
            <el-form-item prop="code">
              <el-input
                style="display: inline-block;"
                name="code"
                v-model="loginForm.code"
                @keyup.enter.native="handleLogin"
                placeholder="请输入验证码"
              >
                <template slot="prefix">
                  <img src="../../assets/icon/saftIcon.png" style="width: 18px;height: 21.63px;margin-top: 12px;margin-left: 13px" alt=""/>
                </template>
                <template slot="suffix">
                  <el-button
                    style="height: 50px ;width: 160px;margin-right: -5px"
                    :type="!btnDisabled ? 'primary' : 'info'"
                    :disabled="btnDisabled"
                    v-debounce="1500"
                    @click="sendCode"
                  >获取验证码{{ btnDisabled ? "(" + countDown + ")" : "" }}</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item style="margin-bottom: 60px; text-align: center;margin-top: 120px">
              <el-button
                style="width: 100%;border-radius: 8px"
                type="primary"
                :loading="loading"
                v-debounce="1500"
                @click.native.prevent="handleLogin"
                >登录</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="current == 0" class="login-form">
          <el-form
            autoComplete="on"
            :model="loginForm"
            :rules="loginRules"
            ref="loginForm"
            label-position="left"
          >
            <el-form-item prop="username">
              <el-input
                name="username"
                type="text"
                v-model="loginForm.username"
                autoComplete="on"
                @input="userNameChange"
                placeholder="请输入账号或手机号"
              >
                <template slot="prefix">
                  <img src="../../assets/icon/phoneIcon.png" style="width: 16px;height: 25.16px;margin-top: 12px;margin-left: 13px" alt="">
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                name="password"
                :type="pwdType"
                @keyup.enter.native="handleLogin"
                v-model="loginForm.password"
                autoComplete="on"
                placeholder="请输入密码"
              >
                <template slot="prefix">
                  <img src="../../assets/icon/lockIcon.png" style="width: 17px;height: 23.15px;margin-top: 12px;margin-left: 13px" alt="">
                </template>
                <div slot="suffix" @click="showPwd" style="margin-top: 5px;margin-right: 10px">
                  <img
                    style="width: 18px; height: 12px; line-height: 16px"
                    :src="pwdType ? require('../../assets/icon/eye.png') : require('../../assets/icon/openEye.png')"
                  />
                </div>
              </el-input>
            </el-form-item>
            <div class="rememberStyle">
              <el-checkbox v-model="rememberType"></el-checkbox>
              <span style="color: #999999;margin-left: 5px">记住密码</span>
            </div>
            <el-form-item style="margin-bottom: 60px; text-align: center">
              <el-button
                style="width: 100%;border-radius: 8px"
                type="primary"
                :loading="loading"
                v-debounce="1500"
                @click.native.prevent="handleLogin"
              >登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isvalidUsername } from "@/utils/validate";
import { setSupport, getSupport, setCookie, getCookie } from "@/utils/support";
import login_center_bg from "@/assets/images/login_center_bg.png";
import { getPhoneCode } from "../../api/login";
import index2 from "./index2.vue";

export default {
  name: "login",
  components: {
    index2
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value == '') {
        callback(new Error("请输入用户名"));
      } else {
        if (!isvalidUsername(value)) {
          callback(new Error("请输入正确的用户名"));
        } else {
          callback();
        }
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value == '') {
        callback(new Error("请输入密码"));
      } else {
        if (value.length < 3) {
          callback(new Error("密码不能小于3位"));
        } else {
          callback();
        }
      }
    };
    const validatorPhone = (rule, value, callback) => {
      let reg = /^1[3456789]\d{9}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    return {
      btnPas: false,
      current: 0,
      rememberType: false,
      loginForm: {
        username: "",
        password: "",
        code: "",
        phoneNumber: "",
        loginType: "normal"
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePass }
        ],
        phoneNumber: [
          { required: true, trigger: "blur", validator: validatorPhone }
        ],
        code: [{ required: true, trigger: "blur", message: "请输入验证码" }]
      },
      loading: false,
      pwdType: "password",
      login_center_bg,
      dialogVisible: false,
      supportDialogVisible: false,
      btnDisabled: false, //发送验证码按钮是否可用
      countDown: 60, //按钮倒计时
      returnPhoneCode: ""
    };
  },
  created() {
    if (localStorage.getItem('adminPassword')) {
      let arr = JSON.parse(localStorage.getItem('adminPassword'))
      if (typeof arr == 'number' || arr.username ) {
        localStorage.setItem('adminPassword', [])
        return
      }
      this.loginForm.password = arr[arr.length - 1].password
      this.loginForm.username = arr[arr.length - 1].username
      if (localStorage.getItem('checked')) {
        this.rememberType = Boolean(localStorage.getItem('checked'))
      }
    }
    this.btnPas = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";

    if (
      this.loginForm.username === undefined ||
      this.loginForm.username == null ||
      this.loginForm.username === ""
    ) {
      // this.loginForm.username = "admin";
    }
    if (
      this.loginForm.password === undefined ||
      this.loginForm.password == null
    ) {
      this.loginForm.password = "";
    }
  },
  methods: {
    tabClick(val) {
      this.current = val
      this.loginForm = {
        username: "",
        password: "",
        code: "",
        phoneNumber: "",
        loginType: val == 0 ? 'normal' : "phone"
      }
      this.$refs.loginForm.resetFields()
      if (localStorage.getItem('adminPassword')) {
        let arr = JSON.parse(localStorage.getItem('adminPassword'))
        arr.forEach(item => {
          if (val == item.username) {
            this.loginForm.password = item.password
            this.loginForm.username = item.username
          }
        })
      }
    },
    userNameChange(val) {
      if(val) {
        if (localStorage.getItem('adminPassword')) {
          let arr = JSON.parse(localStorage.getItem('adminPassword'))
          if (typeof arr == 'number' || arr.username) {
            localStorage.setItem('adminPassword', [])
          } else {
            arr.forEach(item => {
              if (val == item.username) {
                this.loginForm.password = item.password
                this.loginForm.username = item.username
              }
            })
          }
        }
      } else {
        this.loginForm.password = ''
        this.loginForm.username = ''
      }

    },
    rememberChange(val) {
      if (val) {
        if(localStorage.getItem('adminPassword')) {
          let params = {
            username: this.loginForm.username,
            password: this.loginForm.password
          }
          let arr = JSON.parse(localStorage.getItem('adminPassword'))
          arr.push(params)
          localStorage.setItem('adminPassword',JSON.stringify(Array.from(new Set(arr))))
          localStorage.setItem('checked', val)
        } else {
          let params = {
            username: this.loginForm.username,
            password: this.loginForm.password
          }
          localStorage.setItem('adminPassword',JSON.stringify([params]))
          localStorage.setItem('checked', val)
        }
      } else {
        // localStorage.setItem('adminPassword','')
        if(localStorage.getItem('adminPassword')) {
          let arr = JSON.parse(localStorage.getItem('adminPassword'))
          arr.forEach((item,index) => {
            if (item.username == this.loginForm.username) {
              arr.splice(index,1)
            }
          })
          localStorage.setItem('adminPassword',JSON.stringify(arr))
        }
      }
    },
    openDialog() {
      if (this.btnPas) {
        this.$refs.index2.openLog();
      }
    },
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },
    // 发送验证码
    sendCode() {
      let reg = /^1[3456789]\d{9}$/;
      if (this.loginForm.phoneNumber) {
        if (!reg.test(this.loginForm.phoneNumber)) {
          // this.$message.error("请输入正确的手机号码")
          return
        }
        getPhoneCode(this.loginForm.phoneNumber).then(res => {
          if (res.code == 200) {
            this.$message.success("发送成功");
            this.btnDisabled = true;
            let timer = setInterval(() => {
              if (this.countDown > 0) {
                this.countDown--;
              } else {
                clearInterval(timer);
                this.btnDisabled = false;
                this.countDown = 60;
              }
            }, 1000);
          }
        });
      } else {
        if (this.loginForm.phoneNumber == '') {
          this.$message.error("请输入手机号码")
        }
        // else {
        //   if (!reg.test(this.loginForm.phoneNumber)) {
        //     this.$message.error("请输入正确的手机号码")
        //   }
        // }
      }
    },
    phoneInputFun(val) {
      let reg = /^[0-9]+$/;
      if (!reg.test(val)) {
        this.loginForm.phoneNumber = "";
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // let isSupport = getSupport();
          // if(isSupport===undefined||isSupport==null){
          //   this.dialogVisible =true;
          //   return;
          // }
          this.loading = true;
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.loading = false;
              // setCookie("username", this.loginForm.username, 15);
              // setCookie("password", this.loginForm.password, 15);
              if (this.rememberType) {
                this.rememberChange(this.rememberType)
              }
              this.loginForm.username = ''
              this.loginForm.password = ''
              this.$router.push({ path: "/" });
            })
            .catch(() => {
              this.loading = false;
            });
          //  判断接口返回的验证码与输入框是否一致
          // if (this.loginForm.code == this.returnPhoneCode) {
          //
          // } else {
          //   this.$message.error("验证码输入有误")
          // }
        } else {
          // console.log("参数验证不合法！");
          return false;
        }
      });
    },
    handleTry() {
      this.dialogVisible = true;
    },
    dialogConfirm() {
      this.dialogVisible = false;
      setSupport(true);
    },
    dialogCancel() {
      this.dialogVisible = false;
      setSupport(false);
    }
  }
};
</script>

<style lang="scss" scoped>
.login {
  background: url("~@/assets/images/loginIndexBg.png");
  width: 100%;
  height: 100%;
  position: fixed;
  background-size: 100% 100%;

  .login-main {
    position: absolute;
    left: 56%;
    top: 50%;
    transform: translate(0%, -50%);
    display: flex;
    background-color: #fff;
    width: 560px;
    height: 700px;
    box-shadow: 0px 0px 16px 0px rgba(3,56,110,0.2);
    border-radius: 24px;
    .main-left {
      width: 50%;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .main-right {
      width: 50%;
      .logo {
        margin-top: 48px;
        margin-left: 30px;
        width: 156px;
        height: 72px;
        img {
          width: 100%;
          height: 100%;
        }
      }

    }
  }
}
.login-form {
  // margin-top: 50px;
  //padding: 50px 100px;
  width: 80%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
.loginTab {
  display: flex;
  justify-content: flex-start;
  margin-top: 50px;
  .password {
    width: 160px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    color: #999999;
    font-size: 18px;
    position: relative;
    cursor: pointer;
  }
  .bottomLine{
    width: 56px;
    height: 5px;
    margin: 0 auto;
    border-radius: 8px;
    background: #419eff;
  }
  .loginCode {
    width: 160px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 18px;
    color: #999999;
    position: relative;
    cursor: pointer;
  }
  .active {
    color: #222222;
    font-weight: 500;
  }
}

.login-title {
  margin-bottom: 50px;
  text-align: center;
  color: #f2891d;
}

.login-center-layout {
  background: #409eff;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin-top: 200px;
}
/deep/ .el-input__inner {
  height: 50px;
  line-height: 50px;
  //margin-bottom: 20px;
  padding-left: 50px;
}
/deep/ .el-form-item {
  margin-bottom: 30px;
}
/deep/ .el-input__inner:focus {
  // el-input输入时设置边框颜色
  border: #e5e5e5 1px solid !important;
}
/deep/ .el-button--primary {
  height: 50px;
  background-color: #419EFF;
  border: none;
}
.rememberStyle {
  margin-top: 20px;
  margin-bottom: 50px;
}
/deep/ .el-form-item__error {
  //margin-top: -20px;
}
</style>
